package com.bdsy.common.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.multipart.MultipartFile;

public class UpDownUtil {

	// 上传文件
	public static String upload(MultipartFile file,String path,String appVersion) {
		//文件名
	//		String fileName = file.getOriginalFilename();
		 String fileName= null;
		if(file !=null){
				//文件类型
				String contentType = file.getContentType();
				String getOriginalFilename = file.getOriginalFilename(); //获取上传文件的原名
				//获得文件后缀名   
//			    String suffixName=contentType.substring(contentType.indexOf("/")+1); 
				String prefix=getOriginalFilename.substring(getOriginalFilename.lastIndexOf(".")+1);
				//生成uuid作为文件名称    
//			    String uuid = UUID.randomUUID().toString().replaceAll("-","");    
			    //得到 文件名    版本号 作为文件名
			     fileName=appVersion+"."+prefix;  
			    
			    System.out.println(path+"--***---"+contentType+"--***---"+prefix+"---***---"+fileName);
				//生成文件
			    File dir = new File(path, fileName);  
			    if(!dir.exists()){  
			        dir.mkdirs();  
			    }   
			    System.out.println(dir.getAbsolutePath()+"///////");
			    try {
					file.transferTo(dir);
				}catch (IOException e) {
					System.out.println("文件转换失败");
					e.printStackTrace();
				}
				
		}
		return fileName;

	}
	
	// 下载文件
	public static void download(HttpServletRequest request,HttpServletResponse response,String fileName,String filePath) throws IOException{
		
	    try {
			// path是指欲下载的文件的路径。
			String path = filePath + "/" + fileName;
			File file = new File(path);
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			response.reset();
			// 设置response的Header
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
			response.setContentType("application/octet-stream");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException e) {
			 e.printStackTrace();
		}
		
	}
	

}